package cn.mazexal.examapi.controller.notify;

import cn.mazexal.examapi.common.anno.PermitGuest;
import cn.mazexal.examapi.models.thirdpart.wxpay.WxpayNotifyResult;
import cn.mazexal.examapi.services.OrderService;
import cn.mazexal.examapi.services.provider.PayProvider;
import cn.mazexal.examapi.utils.RequestUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: Mazexal
 * Date: 2025/6/30
 */
@RestController
@Tag(name = "notify", description = "回调")
@RequestMapping("/notify/wx")
@Slf4j
public class WxNotifyController {
    @Resource
    private HttpServletRequest request;

    @Resource
    private PayProvider payProvider;
    @Resource
    private OrderService orderService;

    @PostMapping("/wxinPayNotify")
    @PermitGuest
    public WxpayNotifyResult wxinPayNotify() {
        try {
            String xmlData = RequestUtil.httpServletRequestToString(request);
            log.info("微信支付异步通知: {}", xmlData);
            // 验签
            if (payProvider.checkWxPayNotifySign(xmlData)) {
                // 处理订单逻辑
                if (!orderService.handleWxPayNotify(xmlData)) {
                    getNotifyResult("订单处理失败", false);
                }

                return getNotifyResult("订单处理成功", true);
            }
            return getNotifyResult("签名校验失败", false);
        } catch (Exception e) {
            return getNotifyResult("参数格式校验错误", false);
        }
    }

    private WxpayNotifyResult getNotifyResult(String message, boolean isSuccess) {
        log.info(message);
        WxpayNotifyResult notifyResult = new WxpayNotifyResult();
        notifyResult.setReturn_code(isSuccess ? "SUCCESS" : "FAIL");
        notifyResult.setReturn_msg(message);
        return notifyResult;
    }

}
